package com.example.blogother.controller;


import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.plugins.pagination.PageDTO;
import com.example.blogother.mapper.*;
import com.xpd.blog.bean.*;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.Errors;
import org.springframework.web.bind.annotation.*;

import org.yaml.snakeyaml.nodes.CollectionNode;

import javax.validation.Valid;
import java.text.SimpleDateFormat;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.*;
import java.util.stream.Collectors;

/**
 * <p>
 *  前端控制器
 * </p>
 *
 * @author xpd
 * @since 2024-09-19
 */
@RestController
@RequestMapping("/article")
public class ArticleController {
    @Autowired
    ArticleMapper  articleMapper;
    @Autowired
    TypeinfoMapper typeinfoMapper;
    @Autowired
    UserinfoMapper userinfoMapper;
    @Autowired
    FailMapper failMapper;
   /* @RequestMapping("getAllArticle")
    public Result getAllArticle(@RequestBody Article article,
                                @RequestParam int page, @RequestParam int size){
        LambdaQueryWrapper<Article> lqw=new LambdaQueryWrapper<>();
        Long aLong = articleMapper.selectCount(null);
        System.out.println("aLong = " + aLong);
        if(article.getTitle()==null||"".equals(article.getTitle())==false){
            lqw.like(Article::getTitle,article.getTitle());
        }
        System.out.println((page-1)*size);
        List<Article> articles = articleMapper.selectAll((page-1)*size,size);

       return new Result(1,"数量"+aLong,articles);
    }*/
    //得到访问量最多的五个blog

    @RequestMapping("getFiredArt")

    public Result getFiredArt(@RequestParam int page, @RequestParam int size,@RequestParam int usid){
        Page p=new PageDTO(page,size);
        LambdaQueryWrapper<Article> lqw=new LambdaQueryWrapper<>();
        lqw.eq(Article::getUsid,usid);
        Page page1 = articleMapper.selectPage(p, lqw);
        return new Result(1,"查询成功",page1);
    }
    @RequestMapping("getNewBlog")
    public List<Article> getNewBlog(){
        LambdaQueryWrapper<Article> lqw=new LambdaQueryWrapper<>();
        lqw.orderByDesc(Article::getView);
        Page page=new PageDTO(1,6);
        Page page1 = articleMapper.selectPage(page, lqw);
        return page1.getRecords();
    }


    @RequestMapping("getArtByType")
    public Result getArtByType(@RequestBody Article article, @RequestParam int page, @RequestParam int size,@RequestParam (defaultValue = "-1") int tid){
        LambdaQueryWrapper<Article> lqw=new LambdaQueryWrapper<>();
        lqw.eq(Article::getStatus,0);

        Long aLong = articleMapper.selectCount(lqw);
        System.out.println("article.getTitle() = " + article.getTitle());
        if(article.getTitle()!=null && "".equals(article.getTitle())==false){
            Page pa=new PageDTO<Article>(1,5);

            lqw.like(Article::getTitle,article.getTitle());
            Page page1 = articleMapper.selectPage(pa, lqw);
            for (int i = 0; i < page1.getRecords().size(); i++) {
             Article article1= (Article)page1.getRecords().get(i);
                Userinfo userinfo = userinfoMapper.selectById(article1.getUsid());
                Typeinfo typeinfo = typeinfoMapper.selectById(article1.getTid());
                article1.setUserinfo(userinfo);
                article1.setTypeinfo(typeinfo);
            }
            return new Result(1,"搜素查找",page1);
        }else{
            if(tid==-1){
                System.out.println((page-1)*size);
                List<Article> articles = articleMapper.selectAll((page-1)*size,size);
                return new Result(1,""+aLong,articles);
            }else{
                lqw=new LambdaQueryWrapper<>();
                lqw.eq(Article::getTid,tid);
                lqw.eq(Article::getStatus,0);
                aLong = articleMapper.selectCount(lqw);
                System.out.println("aLong = " + aLong);
                List<Article> articles = articleMapper.selectByTidArticles(tid,(page-1)*size,size);
                return new Result(1,""+aLong,articles);
            }
        }
    }

    //首页显示
    @RequestMapping("homePage")
    public Result homePage(@RequestBody Article article, @RequestParam int page, @RequestParam int size,@RequestParam int tid){
        Page p=new PageDTO(page,size);
        LambdaQueryWrapper<Article> lqw=new LambdaQueryWrapper<>();
        if (tid!=-1){
            lqw.eq(Article::getTid,tid);
        }
        if(article.getTitle()!=null&&!"".equals(article.getTitle())){
            lqw.like(Article::getTitle,article.getTitle()).or()
                    .like(Article::getContent,article.getContent());
        }
        lqw.eq(Article::getStatus,0);
        lqw.orderByDesc(Article::getAdate);
        Page page1 = articleMapper.selectPage(p, lqw);
        for (int i = 0; i < page1.getRecords().size(); i++) {
            Article article1= (Article)page1.getRecords().get(i);
            Userinfo userinfo = userinfoMapper.selectById(article1.getUsid());
            Typeinfo typeinfo = typeinfoMapper.selectById(article1.getTid());
            article1.setUserinfo(userinfo);
            article1.setTypeinfo(typeinfo);
        }
        return  new Result(1,"查询成功",page1);
    }


    //根据id来查找
    @RequestMapping("getArtByid")
    public Result  getArtByid(@RequestParam int aid){
        System.out.println("aid = " + aid);
        Article article = articleMapper.selectByAidArticle(aid);
        return new Result(1,"查询成功",article);
    }

    //添加blog

    @RequestMapping("addArticle")
    public Result addArticle(@Valid @RequestBody Article article,Errors errors){
        if(article.getUsid()==null||"".equals(article.getUsid())){
            return new Result(-2,"你还没有登录，请先登录在发blog",null);
        }
       if(errors.hasErrors()){
           return new Result(-1,"博客信息有误请重新输入",errors.getAllErrors());
       }
       if(article.getPower().length()>0){
           for (String s : article.getPower().split(";")) {
               if("私密".equals(s)){
                   article.setStatus(4);
               }
           }
       }
        article.setAdate(LocalDateTime.now());
        article.setStatus(1);
        System.out.println("article.getShowcol() = " + article.getShowcol());
        int insert = articleMapper.insert(article);
        System.out.println("insert = " + insert);
        if(insert>0){
            return new Result(1,"发表成功",null);
        }else{
            return new Result(-1,"发表失败",null);
        }
    }
    @RequestMapping("draftArticle")
    public Result draftArticle(@RequestBody Article article){
        article.setAdate(LocalDateTime.now());
        article.setStatus(-2);
        int insert = articleMapper.insert(article);
        if(insert>0){
            return new Result(1,"存稿成功",null);
        }else{
            return new Result(-1,"存稿成功",null);
        }
    }
    //根据用户id来查找自己的blog有多少点赞的
    @RequestMapping("getAdmire")
    public Result getAdmire(@RequestParam int usid){
        LambdaQueryWrapper<Article> lqm=new LambdaQueryWrapper<>();
        lqm.eq(Article::getUsid,usid);
        List<Article> articles = articleMapper.selectList(lqm);
        int like=0;
        for (int i = 0; i < articles.size(); i++) {
            like+=articles.get(i).getLikes();
        }
        return new Result(1,"查询点赞成功",like);
    }
    //得到自己的blog
    @RequestMapping("getMyBlog")
    public Result getMyBlog(@RequestParam int usid,@RequestParam int page,@RequestParam int size,@RequestParam int status){
        LambdaQueryWrapper<Article> lqm=new LambdaQueryWrapper<>();
        lqm.eq(Article::getUsid,usid);
        lqm.eq(Article::getStatus,status);
        Page p=new PageDTO(page,size);
        Page page1 = articleMapper.selectPage(p, lqm);
        return new Result(1,"查询成功",page1);
    }

    //删除自己的blog
    @RequestMapping("delMyBlog")
    public Result delMyBlog(@RequestParam int aid){
        LambdaQueryWrapper<Article> lqm=new LambdaQueryWrapper<>();
        lqm.eq(Article::getAid,aid);
        int delete = articleMapper.delete(lqm);
        if(delete>0){
            return  new Result(1,"删除成功",null);
        }else{
            return  new Result(-1,"删除失败",null);
        }
    }

    //修改自己的blog
    @RequestMapping("updateArticle")
    public Result updateArticle(@Valid @RequestBody Article article,Errors errors){
        if(errors.hasErrors()){
            return new Result(-2,"信息没有填写完整",errors.getAllErrors());
        }
       if(article.getPower()!=null&&!"".equals(article.getPower())){
           System.out.println("这一段执行了");
           String[] split = article.getPower().split(";");
           for (String s : split) {
               System.out.println("s = " + s);
               if("私密".equals(s)){
                   article.setStatus(4);
                   break;
               }else{
                   article.setStatus(0);
               }
           }

       }
        article.setAdate(LocalDateTime.now());
        int i = articleMapper.updateById(article);
        if(i>0){
            return new Result(1,"修改成功",null);
        }else{
            return new Result(-1,"修改失败",null);
        }
    }
    //根据类别来查找blog
    @RequestMapping("getBlogByType")
    public Result getBlogByType(@RequestParam int aid,@RequestParam int tid){
        List<Article> articles =articleMapper.selectByAidArticles(aid, tid);
        return new Result(1,"查询成功",articles);
    }


    @RequestMapping("getAdminAllArticle")
    public Result getAdminAllArticle(@RequestBody Article article, @RequestParam int page, @RequestParam int size, @RequestParam int tid, @RequestParam String endDate, @RequestParam String startDate, @RequestParam String searchUname) {
        Page p1 = new PageDTO(page, size);
        LambdaQueryWrapper<Article> lqw = new LambdaQueryWrapper<>();

      /*  if (article.getContent() != null && !"".equals(article.getContent())) {
            lqw.like(Article::getTitle, article.getContent());
        }
        if (article.getContent() != null && !"".equals(article.getContent())) {
            lqw.or().like(Article::getContent, article.getContent());
        }*/

        if (article.getContent() != null && !"".equals(article.getContent())) {
            lqw.and(wrapper -> wrapper.like(Article::getTitle, article.getContent())
                    .or().like(Article::getContent, article.getContent()));
        }
       /* if (article.getContent() != null && !"".equals(article.getContent())) {
            lqw.like(Article::getTitle, article.getContent())
                    .or().like(Article::getContent,article.getContent());
        }*/
        List<Integer> usids = getUserinfosBySearchUname(searchUname);
        if (usids != null && !usids.isEmpty()) {
            lqw.in(Article::getUsid, usids);
        }

        lqw = getArticlesByStatusAndDateRange(lqw, article, startDate, endDate);

        if (article.getTid() != 0 && !"".equals(article.getTid())) {
            lqw.eq(Article::getTid, article.getTid());
        }
        lqw.orderByDesc(Article::getAdate);

        Page page1 = articleMapper.selectPage(p1, lqw);
        addUserinfoAndTypeinfoToArticles(page1.getRecords());

        return new Result(1, "查询成功", page1);
    }

    private List<Integer> getUserinfosBySearchUname(String searchUname) {
        if (searchUname == null || "".equals(searchUname)) {
            return null;
        }
        LambdaQueryWrapper<Userinfo> uslqw = new LambdaQueryWrapper<>();
        uslqw.like(Userinfo::getUname, searchUname);
        List<Userinfo> userinfos = userinfoMapper.selectList(uslqw);
        List<Integer> usids = new ArrayList<>();
        for (Userinfo userinfo : userinfos) {
            usids.add(userinfo.getUsid());
        }
        return usids;
    }

    private LambdaQueryWrapper<Article> getArticlesByStatusAndDateRange(LambdaQueryWrapper<Article> lqw, Article article, String startDate, String endDate) {
        if (article.getStatus() != null && !"".equals(article.getStatus())) {
            lqw.eq(Article::getStatus, article.getStatus());
        } else {
            lqw.in(Article::getStatus, 1, 0, -1);
        }
        if (startDate != null && !"".equals(startDate)) {
            lqw.between(Article::getAdate, startDate, endDate);
        }
        return lqw;
    }

    private void addUserinfoAndTypeinfoToArticles(List<Article> articles) {
        for (Article article : articles) {
            Userinfo userinfo = userinfoMapper.selectById(article.getUsid());
            Typeinfo typeinfo = typeinfoMapper.selectById(article.getTid());
            article.setUserinfo(userinfo);
            article.setTypeinfo(typeinfo);
        }
    }



    //修改状态
    @RequestMapping("statusByusid")
    public Result statusByusid(@RequestBody Article article,@RequestParam int status,@RequestParam String content){
        System.out.println("content = " + content);
        LambdaQueryWrapper<Article> lqw=new LambdaQueryWrapper<>();
        lqw.eq(Article::getAid,article.getAid());
        article.setStatus(status);
        if(status==-1){
            Fail fail=new Fail();
            fail.setAid(article.getAid());
            fail.setTime(LocalDateTime.now());
            fail.setContent(content);
            fail.setStatus(1);
            fail.setUsid(article.getUsid());
            int insert = failMapper.insert(fail);
        }
        int update = articleMapper.update(article, lqw);
        if(update>0){
            return new Result(1,"审核成功",null);
        }else{
            return new Result(-1,"审核失败",null);
        }
    }
    @RequestMapping("addView")
    public Result addView(@RequestBody Article article){
        System.out.println("article.getTitle() = " + article.getTitle());
        article.setView(article.getView()+1);
        int i = articleMapper.updateById(article);
        return new Result(1,"新增完毕",null);
    }


    @GetMapping("/countUserNumber")
    public Result countUserNumber()
    {
        LocalDate currentDate = LocalDate.now();
        TreeMap<String, Integer> map = new TreeMap<String, Integer>(); //用来记录每个日期对应的用户数量
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
        Long tmp;
        for (int i = 0; i <7; i++) {
            String dateStr = currentDate.minusDays(i).format(DateTimeFormatter.ofPattern("yyyy-MM-dd"));
            System.out.println("dateStr = " + dateStr);
            List<Article> articles = articleMapper.selectListByAdate(dateStr);
            for (int i1 = 0; i1 < articles.size(); i1++) {
                System.out.println("articles = " + articles.get(i1));
            }
            map.put(dateStr,articles.size());
        }
        return new Result(1,"查询成功",map);
    }

    //查询未通过的blog
    @RequestMapping("getWeiBlog")
    public Result getWeiBlog(@RequestParam int usid,@RequestParam int page,@RequestParam int size){
        LambdaQueryWrapper<Article> lqw=new LambdaQueryWrapper<>();
        Page p=new PageDTO(page,size);
        lqw.eq(Article::getUsid,usid);
        lqw.eq(Article::getStatus,-1);
        Page page1 = articleMapper.selectPage(p, lqw);
        return new Result(1,"查询成功",page1);
    }













}

